<template>
  <div class="loginIndexMain">
    <PageHeader :lang="lang"></PageHeader>
      <!--找回密码页面-->
      <input type="text" name="findPhone" style=" display:none">
      <input type="text" name="findEmail" style=" display:none">
      <input type="text" name="findVerifyCode" style=" display:none">
      <div class="login_Main">
        <router-link class="returnPage" to="/user/login"> {{lang['findPossward return']}} </router-link>
        <h3 class="title findps_itle">{{lang['findPossward fotget password']}}</h3>
        <div class="control-box" v-show="loginType">
          <label>{{lang['findPossward phone number']}}</label>
          <div class="input-wrap phone-wrap">
            <div class="area" :class="{active: isShowAreaList}" @click.stop="areaSelect">{{areaCode ? '+' + areaCode : '+000'}}</div>
           <el-input type="text" name="" :placeholder="lang['findPossward enter Mobile']" v-model="findPhone" ref="findPhone" id="findPhone" oninput="value=value.replace(/[^\d]/g, '')" clearable></el-input>
            <div class="selectAreaList" v-show="isShowAreaList">
              <ul>
                <li v-for="item in countryList" @click="selectList(item.Areacode)">
                  <span class="number">{{item.Areacode ? '+' + item.Areacode : ''}}</span>
                  <span class="name">{{item.Name}}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>

        <div class="control-box" v-show="!loginType">
          <label>{{lang['findPossward eamil number']}}</label>
          <div class="input-wrap">
             <el-input type="text" name="" :placeholder="lang['findPossward enter email']" v-model="findEmail" ref="findEmail" id="findEmail" clearable></el-input>
          </div>
        </div>

        <div class="control-box">
          <label>{{lang['findPossward identifying']}}</label>
          <div class="input-wrap verifyCode-wrap">
            <el-input type="text" name="" :placeholder="lang['findPossward enter identifying']" v-model="findVerifyCode" ref="findVerifyCode" id="findVerifyCode" maxlength="6" clearable></el-input>
            
            <span class="operation active" v-if="sendMsgDisabled">{{lang['register_ClickGett']}}({{time}})</span>
            <span class="operation" :class="{active: !findPhone && !findEmail}" v-if="!sendMsgDisabled" @click="sendVerifyCode">{{lang['register_ClickGet']}}</span>
          </div>
        </div>

        <button type="button" class="buttonBox magTopBox" @click='FindPasswordBth'
          :class="{disabled: !isDisableBtn || (!findPhone && !findEmail) || findVerifyCode.length < 6}">
          {{lang['findPossward next step']}}
        </button>

      </div>
    <div class="errorTip"></div>
    <!-- 验证窗口 -->
    <div class="loginVerifySuccess" v-show="isShowVerify">
      <div class="verifyMain">
       <h3>{{lang['login Sliding verification5']}}</h3>
        <img src="./images/closeverify.png"  @click="closeVerify">
        <div id="your-dom-id" class="nc-container"></div>
      </div>
    </div>
    <!-- 验证窗口 -->
  </div>
</template>

<script>
import commonMixins from '@/mixins/common.js'
import ModalApi from '@/components/SwModal/api.js'
import CheckInput from '@/utils/CheckInput.js'
import rules from '@/utils/rules.js'
import LocalStorage from '@/utils/LocalStorage.js'

export default {
  mixins: [commonMixins],
  data () {
    return {
      time: 60,
      sendMsgDisabled: false,
      countryList: [],
      areaCode: '',
      isShowAreaList: false,
      findPhone: '',
      findEmail: '',
      findVerifyCode: '',
      loginType: true,
      isDisableBtn: true,
      behaviorCode: '',
      isShowVerify: false,
      nc: null
    }
  },
  watch: {
    langKey () {
      this.initCountryList()
      this.aliyun()
    }
  },
  components: {
  },
  methods: {
    setScrollBar () {
      // 滚动条
      this.$nextTick(() => {
        $('.selectAreaList').niceScroll({
          autohidemode: false
        }).resize()
      })
    },
    areaSelect () {
      this.isShowAreaList = !this.isShowAreaList
    },
    selectList (areaCode) {
      this.areaCode = areaCode
      this.isShowAreaList = false
    },
    checkNationality () { //  判断是否选择国籍
      if (!this.areaCode && this.loginType) {
        ModalApi.message(this.lang['41005'])
        return false
      } else {
        return true
      }
    },
    sendVerifyCode () {
      if (!this.findPhone && !this.findEmail) {return}
      if (!this.checkNationality()) { return }
      // 检验手机/邮箱、 验证码是否为空
      this.checkHandle.chackByIdsInOrder([this.loginType ? 'findPhone' : 'findEmail'])
      .then((info) => {
        let top = $('#' + info.id).offset().top
        let currentInput = $('#' + info.id)
        if (!info.isValid) {
          this.errorTip(top, info.error(), currentInput)
          return
        }
        this.isShowVerify = true
      })
      .catch((info) => {
      })
    },
    eventshow (ev) {
      if (ev.keyCode === 13) {
        this.FindPasswordBth()
      }
    },
    // 下一步
    FindPasswordBth () {
      if (!this.isDisableBtn || (!this.findPhone && !this.findEmail) || this.findVerifyCode.length < 6) {
        return
      }
      if (!this.checkNationality()) { return }
      // 检验手机/邮箱、用户名、密码、确认密码、图片验证码是否为空
      this.checkHandle.chackByIdsInOrder([this.loginType ? 'findPhone' : 'findEmail', 'findVerifyCode'])
      .then((info) => {
        let top = $('#' + info.id).offset().top
        let currentInput = $('#' + info.id)
        if (!info.isValid) {
          this.errorTip(top, info.error(), currentInput)
          return
        }
        this.isDisableBtn = false
        this.$http.post('Customer/FindPasswordNextStep', {
          verifyDeviceType: this.loginType ? 1 : 2, // 1.手机；2.邮箱
          clientType: 0, // 0,网页;1,android;2,iOS
          areaCode: this.loginType ? this.areaCode : '',
          phoneOrEmail: this.loginType ? this.findPhone : this.findEmail,
          verifyCode: this.findVerifyCode
        })
        .then((res) => {
          if (res.StatusCode === '200') {
            this.$router.push({
              path: '/user/findPasswordStep2',
              query: {
                verifyCode: this.findVerifyCode,
                areaCode: this.loginType ? this.areaCode : '',
                phoneOrEmail: this.loginType ? this.findPhone : this.findEmail,
              }
            })
          }
          this.isDisableBtn = true
        })
      })
      .catch((info) => {
      })
    },
    initCountryList () {
      this.$http.get('/static/js/data/country_' + this.langKey + '.json', {}, {
        isCustomUrl: true
      }).then((res) => {
        let list = []
        for (let i = 0; i < res.Data.length; i++) {
          for (let j = 0; j < res.Data[i].Data.length; j++) {
            res.Data[i].Data[j].Areacode = res.Data[i].Data[j].Areacode.replace('+', '')
            list.push(res.Data[i].Data[j])
          }
        }
        this.countryList = list
        let index = 0
        let loginPhoneCode = localStorage.getItem('loginPhoneCode')
        if (loginPhoneCode) {
          for (let i = 0; i < this.countryList.length; i++) {
            if (loginPhoneCode === this.countryList[i].Areacode) {
              index = i
            }
          }
          this.areaCode = this.countryList[index].Areacode
        }

        this.setScrollBar()
      })
    },
    hideLangList () {
      this.isShowAreaList = false
    },
    errorTip (top, error, currentInput) {
      $('.errorTip').stop(true,true).css({'top': top -50}).html(error).fadeIn()
      $(currentInput).parent('.el-input').css({"border": "solid 1px #f00"}) // .parents('.input-wrap')
      setTimeout(function () {
        $('.errorTip').fadeOut()
        $(currentInput).parent('.el-input').css({"border": "solid 1px #4E5A84"}) // .parents('.input-wrap')
      }, 2000)
    },
    findPasswordRules () {
      let onchecked = (result) => {
        let top = $('#' + result.id).offset().top
        let currentInput = $('#' + result.id)
        if (!result.isValid && that._.isFunction(result.error)) {
          this.errorTip(top, result.error(), currentInput)
        }
      }
      let that = this
      this.checkHandle = new CheckInput({
        rules: rules,
        trimValue (val, item) {
          return val.replace(/^\s+|\s+$/, '')
        },
        list: [
          {
            id: 'findPhone',
            input: document.getElementById('findPhone'),
            checkOn: ['blur'],
            onchecked,
            rules: [
              {
                rule: 'required',
                error () {
                  return that.lang['findPossward enter Mobile']
                }
              },
              {
                isReverseRule: true,
                rule (val) {
                  return that.areaCode === '86' && val && !/^1\d{10}$/.test(val)
                },
                error () {
                  return that.lang['please enter the correct phone number']
                }
              }
            ]
          },
          {
            id: 'findEmail',
            input: document.getElementById('findEmail'),
            checkOn: ['blur'],
            onchecked,
            rules: [
              {
                rule: 'required',
                error () {
                  return that.lang['findPossward enter email']
                }
              },
              {
                rule: 'email',
                error () {
                  return that.lang['register_EmailErr']
                }
              }
            ]
          },
          {
            id: 'findVerifyCode',
            input: document.getElementById('findVerifyCode'),
            rules: [
              {
                rule: 'required',
                error () {
                  return that.lang['findPossward enter identifying']
                }
              }
            ]
          }
        ]
      })
      // document.getElementById('findPhone').onkeypress = function (e) {
      //   if (e.keyCode < 48 || e.keyCode > 57) {
      //     e.returnValue = false
      //   }
      // }
    },
    closeVerify () {
      this.isShowVerify = false
      this.aliyun()
    },
    aliyun () {
      let self = this
      // ar_SA:阿拉伯文
      // de_DE:德文
      // es_ES:西班牙文
      // fr_FR:法文
      // in_ID:印尼语
      // it_IT:意大利文
      // iw_HE:希伯来语
      // ja_JP:日文
      // ko_KR:韓文
      // nl_NL:荷蘭文
      // pt_BR:波蘭文
      // ru_RU:俄文
      // th_TH:泰文
      // tr_TR:土耳其文
      // vi_VN:越南文
      // cn:简体中文
      // tw:繁体中文
      // en:英文
      let key = ''
      if (self.langKey === 'zh-CN') { key = 'cn'}
      if (self.langKey === 'en') { key = 'en'}
      if (self.langKey === 'zh-Hant') { key = 'tw'}
      if (self.langKey === 'fr') { key = 'fr_FR'}
      if (self.langKey === 'ja') { key = 'ja_JP'}
      if (self.langKey === 'ko') { key = 'ko_KR'}
      if (self.langKey === 'nl') { key = 'nl_NL'}
      if (self.langKey === 'vi') { key = 'vi_VN'}

      let ncToken = ['FFFF0N0000000000635A', (new Date()).getTime(), Math.random()].join(':')
      let ncOpt = {
        renderTo: '#your-dom-id',
        appkey: 'FFFF0N0000000000635A',
        scene: 'nc_login',
        token: ncToken,
        customWidth: '100%',
        trans: { 'key1': 'code0' },
        elementID: ['usernameID'],
        is_Opt: 0,
        language: key,
        isEnabled: true,
        timeout: 3000,
        times: 5,
        apimap: {
        },
        callback (data) {
          self.pcTest(data)
        }
      }
      this.nc = new noCaptcha(ncOpt)
      this.nc.upLang(key, {
        _startTEXT: self.lang['login Sliding verification'], // '请按住滑块，拖动到最右边',
        _yesTEXT: self.lang['login Sliding verification2'], // '验证通过',
        _error300: self.lang['login Sliding verification3'], // '哎呀，出错了，点击<a href=\'javascript:__nc.reset()\'>刷新</a>再来一次',
        _errorNetwork: self.lang['login Sliding verification4'], // '网络不给力，请<a href=\'javascript:__nc.reset()\'>点击刷新</a>',
      })
      self.nc.reset()
    },
    pcTest (data) {
      this.$http.post('Aliyun/PCSlider', {
        csessionid: data.csessionid,
        sig: data.sig,
        token: data.token,
        value: data.value,
        BusinessType: 3 // 0 未知类型， 1 登录， 2注册， 3 找回密码
      }).then((res) => {
        if (res.StatusCode === '200') {
          res.Data = res.Data || {}
          this.behaviorCode = res.Data.BehaviorCode || ''
          this.closeVerify()
          // 发送验证码
          this.$http.post('Customer/SendVerifyCode', {
            verifyDeviceType: this.loginType ? 1 : 2, // 1.手机；2.邮箱
            clientType: 0, // 0,网页;1,android;2,iOS
            businessType: 2, // 1注册发验证码；2找回密码发验证码
            areaCode: this.loginType ? this.areaCode : '',
            phoneOrEmail: this.loginType ? this.findPhone : this.findEmail,
            Code: this.behaviorCode
          })
          .then((res) => {
            if (res.StatusCode === '200') {
              ModalApi.message(this.lang['VerificationCodeSuccessful'])
              // 倒计时
              window.clearInterval(this.interval)
              let self = this
              self.sendMsgDisabled = true
              this.interval = window.setInterval(function () {
                if ((self.time--) <= 0) {
                  self.time = 60
                  self.sendMsgDisabled = false
                  window.clearInterval(self.interval)
                }
              }, 1000)
              // 倒计时
            }
          })
          // 发送验证码
        }
      })
    }
  },
  mounted () {
    this.initCountryList()
    document.addEventListener('click', this.hideLangList)

    if (LocalStorage.get('loginType') === 1) { // 1表示手机 2 表示邮箱
      this.loginType = true
    } else if (LocalStorage.get('loginType') === 2) {
      this.loginType = false
    }

    this.findPasswordRules()
    this.aliyun()
  },
  beforeDestroy () {
    document.removeEventListener('click', this.hideLangList)
    window.clearInterval(this.interval)
  }
}
</script>

<style lang="less">
  .nicescroll-cursors {
    border: none !important;
    background-color: #454e7d !important;
  }
</style>
